import time

import requests
import random
import string
import pymysql
import datetime


# 生成随机的 15 位数字和字母组合
def generate_random_code():
    return ''.join(random.choices(string.ascii_letters + string.digits, k=15))


# 发送请求到第一个接口并获取 order_cards_id
def post_first_request():
    url = "http://1.117.224.100:81/admin/company/seller/user/orders"
    headers = {
        'Cookie': 'nexus_session=eyJpdiI6IllGblhlbFVhS0hUb2x1MzhSd290a3c9PSIsInZhbHVlIjoiT3B6cmVROGVzUEdHZzZucTh5Nko5eElCbmJyWE90TXZ0eTlXV0twbnVQZlZGOUF6YTdWNnFSd1Era3NDSS9JMGMvbWZiUy9wUnFoYWhKbEZGRVc0bTk1Z0RZTWpYSTZGOVFQN2R0bzRnais5NFdUOEk1ano5QXpZQklDdlVobUgiLCJtYWMiOiI1MWY0ZjUwNjU4YmNhMjVlOTc2ZGVkMzM4ZjVmZjU5NGEyZGI4YmVjMTY2NTk5ZTJkZWE1YWQxMGEyNDRlYTNiIiwidGFnIjoiIn0%3D'}
    data = {
        "cards[0][card_id]": 43,
        "cards[0][can_batch_sell]": 1,
        "cards[0][card_info][0][code]": generate_random_code(),
        "cards[0][card_type]": 2,
        "cards[0][country_id]": 1,
        "cards[0][is_fast]": 1,
        "cards[0][machine]": 314,
        "cards[0][operator_id]": 314,
        "cards[0][rate]": 156,
        "cards[0][rmb_rate]": "1.0000",
        "cards[0][balance]": "1",
    }
    response = requests.post(url, data=data, headers=headers)
    response_json = response.json()
    order_cards_id = response_json["order_cards"][0]["id"]
    return order_cards_id


# 查询数据库
def query_database(order_card_id):
    connection = pymysql.connect(
        host='sh-cynosdbmysql-grp-dhfnikj6.sql.tencentcdb.com',
        port=21044,
        user='root',
        password='Moregold!23',
        database='nexus'
    )
    with connection.cursor() as cursor:
        query = "SELECT id FROM `order_card_queues` WHERE order_card_id = %s"
        cursor.execute(query, (order_card_id,))
        result = cursor.fetchone()
        connection.close()
        return result[0] if result else None


# 发送请求到第二个和第三个接口
def post_second_and_third_requests(order_card_id, order_card_queue_id):
    local_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    url2 = "http://1.117.224.100:81/admin/company/buyer/user/check-card-ecode"
    url3 = "http://1.117.224.100:81/admin/company/buyer/user/process-order-card-queue-done"
    headers = {
        'Cookie': 'nexus_session=eyJpdiI6InMvM2U1cXhkbllvenIxaE9ubFN1bUE9PSIsInZhbHVlIjoiS3lxOElyaVFwTVY1cS94cUpISnk0NjlRS2lFUHVvMkE3UUZTUGhoc2YwUFVXTU4wQnF2UUJWbVJsWlIwei9tODNlYkY4cW55WU1ySkx1YWREWHA2eE1vc2RGSWMvRjExOVRXTFhEbWMzcTBzaUc3NUNTdUJHWmdybUJFSCtPaHAiLCJtYWMiOiIyYTBkZWQ4Y2MzOWY0YTAyYmMxZDc5NDcwZGFjOTVhODNiZTE1OGQ4NTNkNjhlNGU5OGEyZmI2ODFmZjczYmM5IiwidGFnIjoiIn0%3D'}
    data2 = {
        "local_time": local_time,
        "order_card_id": order_card_id,
        "order_card_queue_id": order_card_queue_id,
    }
    response2 = requests.post(url2, data=data2, headers=headers)
    if response2.status_code == 200:
        data3 = {
            "card_info": "",
            "company_update_card_info": 0,
            "local_time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            "order_card_queue_id": order_card_queue_id,
        }
        requests.post(url3, data=data3, headers=headers)


# 主函数，设置循环次数
def main(loop_count):
    # 记录开始时间
    start_time_total = time.time()
    for _ in range(loop_count):
        order_card_id = post_first_request()

        # 初始化一个时间戳，用于追踪超时
        start_time = time.time()
        order_card_queue_id = None

        # 持续查询数据库，直到超过10秒或者拿到了order_card_queue_id
        while time.time() - start_time < 10:
            order_card_queue_id = query_database(order_card_id)
            if order_card_queue_id:
                break  # 如果拿到了值，就跳出循环
            time.sleep(0.5)  # 每隔0.2秒查询一次

        # 如果拿到了order_card_queue_id，执行后续请求
        if order_card_queue_id:
            post_second_and_third_requests(order_card_id, order_card_queue_id)
        else:
            print(f"Failed to get order_card_queue_id for order_card_id {order_card_id} within 10 seconds.")
    # 记录结束时间
    end_time_total = time.time()

    # 计算并打印平均时间
    average_time = (end_time_total - start_time_total) / loop_count
    print(f"Average time per loop: {average_time} seconds")


# 运行脚本
if __name__ == "__main__":
    LOOP_COUNT = 1  # 你想要的循环次数
    main(LOOP_COUNT)
